#include <stm32l1xx.h>
#include <init.h>
#include <usart.h>
#include <adc.h>

void set_clock(void) {

}

void init_IO(void) {
	RCC -> AHBENR    |= RCC_AHBENR_GPIOAEN | RCC_AHBENR_GPIOBEN | RCC_AHBENR_GPIOCEN | RCC_AHBENR_DMA1EN; // enable GPIOA, GPIOB, GPIOC, DMA1 (CH4 - USART1_TX)
	RCC -> APB1ENR   |= RCC_APB1ENR_COMPEN | RCC_APB1ENR_TIM2EN | RCC_APB1ENR_TIM3EN | RCC_APB1ENR_TIM4EN | RCC_APB1ENR_TIM5EN | RCC_APB1ENR_TIM6EN;                      // TIM2/3/4/5/6 (PWMmot, PWM, IRC, timebase), operaky
	RCC -> APB2ENR   |= RCC_APB2ENR_USART1EN | RCC_APB2ENR_ADC1EN;                    // enable USART1 and ADC

	
	RCC -> APB1RSTR  |=   RCC_APB1RSTR_TIM4RST;
	RCC -> APB1RSTR  &= ~(RCC_APB1RSTR_TIM4RST);
	RCC -> APB1RSTR  |=   RCC_APB1RSTR_TIM3RST;
	RCC -> APB1RSTR  &= ~(RCC_APB1RSTR_TIM3RST);
	RCC -> APB1RSTR  |=   RCC_APB1RSTR_TIM2RST;
	RCC -> APB1RSTR  &= ~(RCC_APB1RSTR_TIM2RST);
	RCC -> APB1RSTR  |=   RCC_APB1RSTR_COMPRST;
	RCC -> APB1RSTR  &= ~(RCC_APB1RSTR_COMPRST);
	
	GPIOA -> MODER   |= GPIO_MODER_MODER9_1 | GPIO_MODER_MODER10_1; // alternate for PA9 and PA10
	GPIOA -> OSPEEDR |= GPIO_OSPEEDER_OSPEEDR9 | GPIO_OSPEEDER_OSPEEDR10; // 50 MHz
	GPIOA -> AFR[1]  |= (0x00000770); // USART

	GPIOB -> MODER   |= GPIO_MODER_MODER10_1 | GPIO_MODER_MODER11_0 | GPIO_MODER_MODER12_0; // Output mode for PB7, alternate for PB6 /10
	GPIOB -> OSPEEDR |= GPIO_OSPEEDER_OSPEEDR10 | GPIO_OSPEEDER_OSPEEDR11 | GPIO_OSPEEDER_OSPEEDR12; // 50 MHz 
	GPIOB -> AFR[1]  |= (0x00000100); // PB10, TIM2_PWM CH3
	GPIOB -> AFR[0]  |= (0x02000000); // pwm na PB6
	GPIOB -> BSRRH = 1 << 7;	

	GPIOC -> MODER   |= GPIO_MODER_MODER0_0 | GPIO_MODER_MODER1_0 | GPIO_MODER_MODER2_0 | GPIO_MODER_MODER3_0 | GPIO_MODER_MODER6_1 | GPIO_MODER_MODER7_1; // PC3-0 out, PC7/6 alternate
	GPIOC -> OSPEEDR |= GPIO_OSPEEDER_OSPEEDR7 | GPIO_OSPEEDER_OSPEEDR6 | GPIO_OSPEEDER_OSPEEDR0;
	GPIOC -> ODR     |= 0x00000000;
	GPIOC -> AFR[0]  |= (0x22000000); // PC6/7, TIM3
	GPIOC -> PUPDR   |= GPIO_PUPDR_PUPDR6_0 | GPIO_PUPDR_PUPDR7_0;

	SET_BIT(RCC -> CR,RCC_CR_HSION); // HSI on (for ADC)
	RCC -> CFGR |= RCC_CFGR_SW_HSI;
#define SYSCLK 16000000L
	
	TIM4 -> PSC = 1600; // f=16MHz/1600=10 kHz
	TIM4 -> ARR = 10000;  // frekvencia PWM 1 Hz
	TIM4 -> CCR1 = 5000;  // plnenie 50%
	TIM4 -> CCMR1 |= TIM_CCMR1_OC1FE | TIM_CCMR1_OC1PE | TIM_CCMR1_OC1M_1 | TIM_CCMR1_OC1M_2;
	TIM4 -> CCER |= TIM_CCER_CC1E;
	TIM4 -> CR1 |= TIM_CR1_CEN; // enable TIMER 4
}
